package com.snow.springboot.service;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Package: com.snow.springboot.service
 * @ClassName: ExcelService
 * @Description:Excel操作service
 * @author: lurui
 * @Date: 2018/10/23 下午12:45
 * @version:
 */
@Service
public class ExcelService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelService.class);


    /**
     * @Description: 解析EXCEL文件
     * @MethodName: readFromFile
     * @Param: [filePath, listenner]
     * @Return: java.util.List<com.snow.springboot.pojo.domain.DiagnoseInfo>
     * @Author: lurui
     * @Date: 2018/10/30 2:33 PM
     */
    public List readFromFile(String filePath, BaseListenner listenner, Class object) {
        if (StringUtils.isEmpty(filePath)) {
            throw new IllegalArgumentException("filePath不能为空");
        }
        if (null == listenner) {
            throw new NullPointerException("excel handel不能为空");
        }
        File file = new File(filePath);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            // 解析每行结果在listener中处理
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listenner);
            excelReader.read(new Sheet(1, 1, object));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return listenner.getDatas();
    }


}
